package netty.im.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;

public class RequestParser {
	
	 private HttpRequest fullReq;

	    /**
	     * 构造一个解析器
	     * @param req
	     */
	    public RequestParser(HttpRequest req) {
	        this.fullReq = req;
	    }

	    /**
	     * 解析请求参数
	     * @return 包含所有请求参数的键值对, 如果没有参数, 则返回空Map
	     *
	     * @throws BaseCheckedException
	     * @throws IOException
	     */
	    public Map<String, String> parse() throws IOException {
	        HttpMethod method = fullReq.method();

	        Map<String, String> parmMap = new HashMap<>();

	        if (HttpMethod.GET == method) {
	            // 是GET请求
	            QueryStringDecoder decoder = new QueryStringDecoder(fullReq.uri());
	            Map<String, List<String>> parame = decoder.parameters();  
                Iterator<Entry<String, List<String>>> iterator = parame.entrySet().iterator();
                while(iterator.hasNext()){
                    Entry<String, List<String>> next = iterator.next();
                    parmMap.put(next.getKey(), next.getValue().get(0));
                }
	        } else if (HttpMethod.POST == method) {
	            // 是POST请求
	            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullReq);
	            decoder.offer((HttpContent) fullReq);
	            List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas();

	            for (InterfaceHttpData parm : parmList) {

	                Attribute data = (Attribute) parm;
	                parmMap.put(data.getName(), data.getValue());
	            }

	        } else {
	        	
	        }

	        return parmMap;
	    }
}
